<template>
  <scroll-view
      id="messagesContainer"
      style="height: 100%;"
      scroll-y="true"
      :scroll-into-view="bottomId"
  >
    <view id="messageList" class="message-list">
      <view
          v-for="item in messages"
          :key="item.ID"
          class="message-list-item"
          :class="item.flow"
          :data-type="item.m_type"
      >
        <view class="message-list-item__time">{{ parseTime(item.time) }}</view>
        <TextMessage v-if="item.m_type === 'TextMessage'" :item="item" />
        <ImageMessage v-else-if="item.m_type === 'ImageMessage'" :item="item" />
        <FileMessage v-else-if="item.m_type === 'FileMessage'" :item="item" />
        <WorkMessage v-else-if="item.m_type === 'WorkMessage'" :item="item" />
        <ServiceMessage v-else-if="item.m_type === 'ServiceMessage'" :item="item" />
        <view :id="`m_${item.ID}`" style="text-align: center;color:red;"></view>
      </view>
      <view id="bottomAnchor"></view>
    </view>
  </scroll-view>
</template>
<script>
import TextMessage from './renderers/TextMessage.vue'
import ImageMessage from './renderers/ImageMessage.vue'
import FileMessage from './renderers/FileMessage.vue'
import WorkMessage from './renderers/WorkMessage.vue'
import ServiceMessage from './renderers/ServiceMessage.vue'
import { parseTime } from '../utils/common'

export default {
  components: {
    TextMessage,
    ImageMessage,
    FileMessage,
    WorkMessage,
    ServiceMessage,
  },
  props: {
    messages: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      bottomId: 'bottomAnchor',
      scrollTop: 0,
    }
  },
  watch: {
    messages: {
      immediate: true,
      deep: true,
      handler(value) {
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      }
    }
  },
  methods: {
    parseTime,
    // 滚动消息底部
    scrollToBottom() {
      if (this.messages.length <= 3) return

      const lastIndex = this.messages.length - 1
      if (this.messages[lastIndex]?.ID) {
        this.bottomId = `m_${this.messages[lastIndex].ID}`;
        console.log('this.bottomId ---->', this.bottomId)
      } else {
        this.bottomId = 'bottomAnchor'
      }
    },
  }
}
</script>
